# coding=utf-8
'''
Created on 2012-7-6

@author: wb_suoyao.shen
'''
from django.db import models,connection
from ssyblog.tags.recdtags import RecdTags
from ssyblog.tags.recdtags import RecdDiary

class TagsManager(models.Manager):
    def tags_list(self,recommend = 'off',count = None):
        if count:
            return self.all().filter(recommend__contains = recommend)[count]
        else:
            return self.all().filter(recommend__contains = recommend)
    def recod_tags_list(self,recommend = 'on',tag_count = 4, diary_count = 3):
        tag_sql = 'SELECT name FROM tags_tags WHERE recommend = %s ORDER BY modify_time DESC LIMIT %s '
        diary_sql = 'SELECT id,title FROM diary_diary WHERE diary_tag = %s ORDER BY modify_time DESC LIMIT %s '
        tags_row = self.querySetRow(tag_sql, [recommend,tag_count])
        tags_list = []
        for row in tags_row:
            tag_name = row[0]
            recd_tag = RecdTags(tag_name = tag_name,diary_list = [])
            diarys_row = self.querySetRow(diary_sql,[tag_name,diary_count])
            for r in diarys_row:
                recd_diary = RecdDiary(diary_id = r[0],diary_title = r[1])
                recd_tag.add_diary(recd_diary)
            tags_list.append(recd_tag)
        return tags_list
    
    def querySetRow(self,sql,param):
        cursor = connection.cursor()
        cursor.execute(sql,param)
        row = cursor.fetchall()
        cursor.close()
        return row

class Tags(models.Model):
    name = models.CharField(max_length=256,null=True)
    description = models.CharField(max_length=5120,null=True)
    write_time = models.DateTimeField(null=True,blank=True)
    modify_time = models.DateTimeField(null=True,blank=True)
    recommend = models.CharField(max_length=32,null=True,blank=True) # 'on' and 'off'
    objects = TagsManager()
    
    def __unicode__(self):
        return self.album_type
    
    class Meta:
        ordering = ['-modify_time']
        
    class Admin:
        list_display = ('name','description','write_time','modify_time','recommend',)
        fields = (
            (None, {'fields':('name','description','write_time','modify_time','recommend')}),
        )